﻿namespace Shanda.DevFx.Security.Web.Pages
{
    using Shanda.DevFx.Core;
    using Shanda.DevFx.ExceptionManagement.Web;
    using Shanda.DevFx.Security;
    using Shanda.DevFx.Security.Sso;
    using Shanda.DevFx.Utils;
    using System;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public class SsoPage : Page
    {
        protected LinkButton btnLogin;
        protected HyperLink hlkLocal;
        protected HyperLink hlkRemote;
        protected Label lblMessage;
        protected Label lblReceiveMsg;

        protected virtual void btnLogin_Click(object sender, EventArgs e)
        {
            this.RedirectToRemote();
        }

        protected virtual void DoAuthenticate(string userName)
        {
            Authentication authentication = base.get_User() as Authentication;
            if (authentication == null)
            {
                this.lblMessage.set_Text("配置错误");
            }
            else
            {
                IAOPResult result = authentication.Authenticate(userName, string.Empty, new object[] { Securitor.Authenticator });
                if (!result.IsSuccess)
                {
                    this.lblMessage.set_Text("登录失败：" + result.ResultDescription);
                }
                else
                {
                    HttpCookie authCookie = authentication.GetAuthCookie();
                    base.get_Response().AppendCookie(authCookie);
                    base.get_Response().Redirect(authentication.GetRedirectUrl(base.get_Request()));
                }
            }
        }

        protected virtual void ErrorHandle(string message)
        {
            this.lblMessage.set_Text(message);
        }

        protected virtual void InitData()
        {
            if (!(Securitor.Authenticator is Shanda.DevFx.Security.Sso.SsoAuthenticator))
            {
                throw new PageException("配置错误&lt;SsoAuthenticator&gt;");
            }
            if (!Shanda.DevFx.Security.Sso.SsoAuthenticator.SsoEnabled)
            {
                WebHelper.ShowMessage("SSO已禁用，请从本地认证", string.Format("window.top.location.href='login.aspx?{0}'", base.get_Request().get_QueryString()), true, true);
            }
            if (!base.get_IsPostBack())
            {
                this.lblReceiveMsg.set_Text(base.get_Request().get_Params()["ErrorMsg"]);
                if (base.get_User().get_Identity().get_IsAuthenticated())
                {
                    this.lblMessage.set_Text(string.Format("您已经作为 <u>{0}</u> 登录了，是否要换个帐号登录？", base.get_User().get_Identity().get_Name()));
                }
            }
            this.hlkRemote.set_NavigateUrl(Shanda.DevFx.Security.Sso.SsoAuthenticator.SsoAuthUrl);
            this.hlkLocal.set_NavigateUrl(string.Format("login.aspx?{0}", base.get_Request().get_QueryString()));
            string str = base.get_Request().get_QueryString()["c"];
            if (str == "remote")
            {
                this.LoginFromRemote();
            }
            else if (Securitor.Authentication.IsAnonymous)
            {
                this.RedirectToRemote();
            }
        }

        private void InitializeComponent()
        {
            this.btnLogin.add_Click(new EventHandler(this.btnLogin_Click));
        }

        protected virtual void LoginFromRemote()
        {
            string str = base.get_Request().get_QueryString()["c"];
            string str2 = base.get_Request().get_QueryString()["ReturnUrl"];
            string str3 = base.get_Request().get_QueryString()["e"];
            string str4 = base.get_Request().get_QueryString()["i"];
            string str5 = base.get_Request().get_QueryString()["a"];
            string userName = base.get_Request().get_QueryString()["u"];
            string str7 = base.get_Request().get_QueryString()["n"];
            string s = base.get_Request().get_QueryString()["t"];
            string str9 = base.get_Request().get_QueryString()["o"];
            string str10 = base.get_Request().get_QueryString()["m"];
            string strA = base.get_Request().get_QueryString()["s"];
            DateTime minValue = DateTime.MinValue;
            int num = 60;
            try
            {
                minValue = DateTime.Parse(s);
            }
            catch
            {
                this.ErrorHandle("时间有误");
                return;
            }
            try
            {
                num = int.Parse(str9);
            }
            catch
            {
                this.ErrorHandle("时间偏移有误");
                return;
            }
            if (Math.Abs(minValue.Subtract(DateTime.Now).TotalSeconds) > num)
            {
                this.ErrorHandle("时间超时");
            }
            else
            {
                if (str5 != Shanda.DevFx.Security.Sso.SsoAuthenticator.SsoAppNo)
                {
                    this.ErrorHandle("应用系统代码错误");
                }
                bool flag = false;
                string str12 = string.Format("c={0}&{1}={2}&e={3}&i={4}&a={5}&u={6}&n={7}&t={8}&o={9}&m={10}", new object[] { str, "ReturnUrl", HttpUtility.UrlEncode(str2), str3, str4, str5, userName, str7, s, str9, str10 });
                string strB = Encryption.Encrypt(this.ToBase64(str12) + Shanda.DevFx.Security.Sso.SsoAuthenticator.SsoAuthKey, "md5");
                if (string.Compare(strA, strB, true) == 0)
                {
                    if (Math.Abs(minValue.Subtract(DateTime.Now).TotalSeconds) > num)
                    {
                        this.ErrorHandle("时间超时");
                        return;
                    }
                    flag = true;
                }
                if (flag)
                {
                    this.DoAuthenticate(userName);
                }
                else
                {
                    this.ErrorHandle("非法请求！");
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            this.InitializeComponent();
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.InitData();
        }

        protected virtual void RedirectToRemote()
        {
            string redirectUrl = Securitor.Authentication.GetRedirectUrl(base.get_Request());
            string str2 = base.get_Response().get_ContentEncoding().get_HeaderName();
            string str3 = this.GetHashCode().ToString();
            string ssoAppNo = Shanda.DevFx.Security.Sso.SsoAuthenticator.SsoAppNo;
            string str5 = string.Format("{0}?c=remote&{1}={2}", base.get_Request().get_Url().GetLeftPart(UriPartial.Path), "ReturnUrl", HttpUtility.UrlEncode(redirectUrl));
            string str6 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string str7 = Shanda.DevFx.Security.Sso.SsoAuthenticator.SsoOffsetTime.ToString();
            string str8 = string.Empty;
            string s = string.Format("e={0}&i={1}&a={2}&r={3}&t={4}&o={5}&m={6}", new object[] { str2, str3, ssoAppNo, str5, str6, str7, str8 });
            s = Encryption.Encrypt(this.ToBase64(s) + Shanda.DevFx.Security.Sso.SsoAuthenticator.SsoAuthKey, "md5");
            string str10 = string.Format(Shanda.DevFx.Security.Sso.SsoAuthenticator.SsoAuthUrl + "?e={0}&i={1}&a={2}&r={3}&t={4}&o={5}&m={6}&s={7}", new object[] { str2, str3, ssoAppNo, HttpUtility.UrlEncode(str5), HttpUtility.UrlEncode(str6), str7, HttpUtility.UrlEncode(str8), s });
            WebHelper.ShowMessage("正在转向远程认证......", string.Format("window.top.location.href='{0}'", str10), true, false);
        }

        private string ToBase64(string s)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(s));
        }
    }
}

